﻿using BulkUploadGovernanceFiles.Models;
using BulkUploadGovernanceFiles.MongoSpecification;
using System;
using System.Collections.Generic;
using System.IO;

namespace BulkUploadGovernanceFiles.SyncroniseInsights
{
    public class ProcessCompanyProfile
    {
        private readonly GovernanceProfileRepository _governanceProfileRepository;
        private readonly MongoGridFSRepository _corporateDataMongoGridFsRepository;

        public ProcessCompanyProfile()
        {
            _governanceProfileRepository = new GovernanceProfileRepository();
            string connectionString = ConfigManager.ClientDw.ConnectionString;
            string dataBaseName = ConfigManager.ClientDw.DataBaseName;
            _corporateDataMongoGridFsRepository = new MongoGridFSRepository(dataBaseName, connectionString);
        }

        public GovernanceProfile GetGovernanceProfileById(Guid companyId)
        {
            return _governanceProfileRepository.GetBy(new GovenanceProfileById(companyId));
        }

        public void Process()
        {
            IEnumerable<GovernanceProfile> companies = _governanceProfileRepository.GetAll();
            foreach (var profile in companies)
            {
                ProcessGovernanceCompanyProfile processGovernanceCompanyProfile = new ProcessGovernanceCompanyProfile(profile.Id);
                if (processGovernanceCompanyProfile.GovernanceCompanyProfile != null)
                {
                    processGovernanceCompanyProfile.UpdateAnalystViewAndInsights(profile);
                    foreach (var alert in profile.Alerts)
                    {
                        GovernanceInsightInputFile insightInputFile = new GovernanceInsightInputFile();
                        var stream = GetAllertFile(alert.FileId);
                        var fileName = stream.Item2;
                        insightInputFile.CompanyId = profile.Id;

                        insightInputFile.Id = Guid.NewGuid();
                        insightInputFile.FileId = alert.FileId;
                        insightInputFile.FileName = fileName;
                        insightInputFile.CreationTimeStamp = alert.CreatedDate.ToString();

                        processGovernanceCompanyProfile.CreateInsightFileMetadata(insightInputFile);

                        processGovernanceCompanyProfile.SavePdfFileToMongo(insightInputFile.FileId, stream.Item2, stream.Item1);
                    }
                }
            }
        }

        public Tuple<Stream, string, string> GetAllertFile(Guid fileId)
        {
            Tuple<Stream, string, string> ret = _corporateDataMongoGridFsRepository.ReadStreamFromMongoFs(fileId);
            return ret;
        }
    }
}
